<template>
  <el-dialog
    :close-on-click-modal="false"
    width="55%"
    :title="title"
    :visible.sync="visible"
    :before-close="close"
    lock-scroll
    append-to-body
  >
    <el-form
      status-icon
      :model="datas"
      @keyup.enter.native="save"
      ref="editForm"
    >
      <el-row :gutter="10">
        <el-col :span="23">
          <el-form-item
            prop="name"
            label="角色名称"
            :label-width="baseStyle.width"
          >
            <el-input
            size="small"
              v-model="datas.name"
              :readonly="false"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
         <el-col :span="23">
          <el-form-item
            prop="name"
            label="数据范围"
            :label-width="baseStyle.width"
          >
            <el-select size="small" v-model="datas.dataScope" placeholder="请选择数据范围">
              <el-option value="全部" label="全部"></el-option>
              <el-option value="本级" label="本级"></el-option>
              <el-option value="自定义" label="自定义"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
         <el-col :span="23" v-show="datas.dataScope==='自定义'">
          <el-form-item
            prop="name"
            label="数据范围"
            :label-width="baseStyle.width"
          >
            <treeselect
            placeholder="请选择组织范围"
              :multiple="true"
              :options="options"
              noChildrenText=""
              @select="selected"
              v-model="datas.deptsId"
              :normalizer="normalizer"
            >
            <!-- loadingText="加载中..." -->
             <!-- :load-options="loadOptions" -->
            <!-- <div slot="value-label" slot-scope="{ node }">{{ node.raw.orgname }}</div> -->
            <!-- <div slot="option-label" slot-scope="{ node }">{{ node.raw.orgname }}</div> -->
            </treeselect>

          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item
            size="small"
            
            prop="description"
            label="描述"
            :label-width="baseStyle.width"
          >
            <el-input
            type="textarea"
            :rows="2"
              v-model="datas.description"
              :readonly="false"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="23">
          <el-form-item
            prop="demo"
            label="菜单权限"
            id="menu_auth_select"
            :label-width="baseStyle.width"
          >
            <el-tree :props="props" ref="treenode" 
                  :tree="tree" :node-key="nodeKey" 
                  check-strictly @check="menuChange" 
                   :default-checked-keys="checkedKeys" 
                  show-checkbox :load="loadNode" lazy>
            </el-tree>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button :type="'primary'" :loading="loading" @click.native="save()"
        >保存</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { Message } from "element-ui";
import menuApi from '@apis/menu'
import deptApi from '@apis/organize'
import Treeselect from '@riophae/vue-treeselect'
import { LOAD_ROOT_OPTIONS, LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: "ClassicForm",
  props: {
    visible: Boolean,
    baseStyle: Object,
    title: String,
    saveForm: Function,
  },
  components: {Treeselect},
  computed:{
    checkedKeys(){
      if(this.datas&&!this.datas.menus){
          return []
      }
      return this.datas.menus.map(_m=>_m[this.nodeKey])
    }
  },
  data() {
    return {
      loading: false,
      tree: [],
      datas: { rolesname: "", exp_time: "", menus:[], dataScope:'' },
      props: {
        label: 'title',
        children: 'hasChildren',
        isLeaf: 'leaf'
      },
      depts:null,
      menuIds: [],
      options: null,
      selectedOptions: [],
      nodeKey: 'menuId' // menuId ; title
    }
  },
  created(){
    deptApi.getAllDept().then(res=>{
      this.options = res
    })
  },
  methods: {
    cancel() {
      this.loading = false;
      this.$emit("update:visible", false);
      this.$refs.editForm.resetFields();
    },
    close() {
      this.cancel();
    },
    setData(data){
      this.menuIds = []
      const _this = this
      if(data.menus){
         data.menus.forEach(function(i) {
          _this.menuIds.push(i[_this.nodeKey])
        })
      }
      if(data.depts){
        data.deptsId =  data.depts.map(i=>i.id)
      }
      // if(data.depts && data.dataScope==='自定义'){
      //   this.getSupDepts(data.depts)
      // }
      this.$nextTick(()=>{
        this.$refs.treenode&&this.$refs.treenode.setCheckedKeys(this.menuIds)
      })
      this.datas = data
    },
     getSupDepts(depts) {
      deptApi.getDeptSuperior({ids:depts}).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.options = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    save() {
      // this.datas.menus = this.$refs.treenode.getCheckedNodes().map(_i=>{return {menuId:_i.menuId}})
      this.datas.menus = this.menuIds.map(_i=>{return {menuId:_i}})
      const _this = this
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if(this.datas.dataScope !== '自定义'){
            this.datas.depts = []
          }else{
            this.datas.depts = []
            for(let i of this.datas.deptsId){
              const temp = this.selectedOptions.filter(item=>item.id===i)
              if(temp.length){
                 _this.datas.depts.push({...temp[0]})
              }
            }
          }
          this.$emit("saveForm", { ...this.datas });
          // this.cancel();
        } else {
          return false;
        }
      });
    },
    getRules() {
      return {
        rolesname: [
          {
            validator: (rule, value, callback) => {
              if (!this.datas.rolesname) {
                callback(new Error(`请填写角色名称`));
                return;
              }
              if (this.datas.rolesname.trim().length < 1) {
                callback(new Error(`请填写角色名称`));
                return;
              }
              callback();
            },
            trigger: "blur",
          },
        ]
      };
    },
    loadNode(node, resolve){
      if(node.level === 0){
        menuApi.getMenus(0).then(res=>{
          this.tree = res
           resolve(res)
        })
      }else{
        menuApi.getMenus(node.data.menuId).then(res=>{
          if(res&&res.length){
            this.createTree(this.tree,node.data.menuId,res)
          }
           resolve(res)
        })
      }
    },
    createTree(data,menuId,res){
      data.map(_i=>{
        if(_i.menuId === menuId){
          _i.children = res
          return true
        }
        if(_i.children){
          this.createTree(_i.children,menuId,res)
        }
      })
    },
    async toggleChildNode(node,checked,menuIds){
      if(!node.children&&!node.leaf){
            await menuApi.getMenus(node.menuId).then(res=>{
               this.createTree(this.tree,node.menuId,res)
            node.children = res
          })
      }
      if(node.children){
        node.children.map(_i=>{
          _i.checked=checked
          const index = menuIds.indexOf(_i[this.nodeKey])
          if(!_i.checked){
            if (index !== -1) {
              menuIds.splice(index, 1)
            }
          }else{
            if (index === -1) {
              menuIds.push(_i[this.nodeKey])
            }
          }
          this.toggleChildNode(_i,checked,menuIds)
          })
      }else{
        return true
      }
    },
    async menuChange(menu,state) {
    // 获取该节点的所有子节点，id 包含自身
    // let menuIds = this.$refs.treenode.getCheckedNodes().map(res=>res[this.nodeKey])
    let menuIds = this.menuIds
    menu.checked = state.checkedKeys.includes(menu.menuId)
    await this.toggleChildNode(menu,menu.checked,menuIds)
    const index = menuIds.indexOf(menu[this.nodeKey])
    if(menu.checked){
      if(index === -1){
        menuIds.push(menu[this.nodeKey])
      }
    }else{
      if (index !== -1) {
        menuIds.splice(index, 1)
      }
    }
    this.$refs.treenode.setCheckedKeys(menuIds)
    // menuApi.getMenus(menu.menuId).then(res => {
    //   const childIds = res
    //   // 判断是否在 menuIds 中，如果存在则删除，否则添加
    //   if (menuIds.indexOf(menu.title) !== -1) {
    //     for (let i = 0; i < childIds.length; i++) {
    //       const index = menuIds.indexOf(childIds[i].title)
    //       if (index !== -1) {
    //         menuIds.splice(index, 1)
    //       }
    //     }
    //   } else {
    //     for (let i = 0; i < childIds.length; i++) {
    //       const index = menuIds.indexOf(childIds[i].title)
    //       if (index === -1) {
    //         menuIds.push(childIds[i].title)
    //       }
    //     }
    //   }
    //   this.$refs.treenode.setCheckedKeys(menuIds)
    // })
  },
  loadOptions({ action, parentNode, callback }){
    if(action==='LOAD_ROOT_OPTIONS'){
      deptApi.getDeptLazy({pid:0}).then(res=>{
        this.options = res
        callback()
      })
    }
    if(action==='LOAD_CHILDREN_OPTIONS'){
        deptApi.getDeptLazy({pid:parentNode.id}).then(res=>{
          parentNode.children = res
          callback()
        })
    }
  },
  normalizer(node) {
    let nodeData = {
        id: node.id,
        label: node.orgname,
        children: node.children ? node.children:undefined
      }
      this.selectedOptions.push(node)
    return nodeData
    },
  selected(node){
    const ids = this.selectedOptions.map(i=>i.id)
    if(ids.includes(node.id)){
      return
    }else{
      this.selectedOptions.push(node)
    }
  },
  }
};
</script>
<style lang="css" scoped>
#menu_auth_select >>> .el-form-item__content{
  height: 200px;
  overflow: auto
}
</style>